package com.m7788.screen;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.m7788.dao.UploadProDataDaoImpl;
import com.m7788.po.UploadInfo;
import com.m7788.po.UploadProData;
import com.m7788.po.UploadResult;
import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.util.DialogUploadFile;
import com.m7788.util.DialogUploadFile.OnChooseFileListener;
import com.m7788.util.HttpService;
import com.m7788.util.ImageUpload;
import com.m7788.view.UmengBaseActivity;
import com.tool.utils.DataUtil;
import com.tool.utils.DateUtil;

public class SinglePhotoScreen extends UmengBaseActivity implements OnClickListener {
	Button  btn_return,btn_roll,btn_submit_1,btn_submit_2,btn_file,btn_right;
	TextView tv_file,sps_text_title;
	ImageView image1;
	Bitmap gbitmap;
	File file;
	Map<String, String> parmasMap = new HashMap<String, String>();
	String mFilePath,Oper,type,params;
	String gpid,gFolderName;
	private String wapFrom;
	ArrayList<UploadInfo> infoList;
	UploadProData proData;
	int canTemp=0;
	int curing=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.single_photo_screen);
		
		initDBdata();
		initView();
//		Log.e("SinglePhotoScreen", "onCreate");
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (gbitmap != null && !gbitmap.isRecycled()){
			gbitmap.recycle();
			gbitmap= null;
 			System.gc();
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		
//		mFilePath = AppUtil.getRecord(this, Constant.SinglePhoto);
//		gbitmap = ImageUpload.readBitmapFromPath(mFilePath);
//		String degreeStr =AppUtil.getRecord(this, Constant.SINGLE_DEGREE);
//		float degree = Float.valueOf("".equals(degreeStr)?"0":degreeStr);
//		gbitmap = AppUtil.rotate(gbitmap, degree);
		int maxSize=0;
		mFilePath = AppUtil.getRecord(this, Constant.SinglePhoto);
		float degree = AppUtil.readPictureDegree(mFilePath); 
		
		String maxTemp = parmasMap.get("maxsize");
		if(maxTemp!=null&& maxTemp.length()>0){
			maxSize = Integer.valueOf(maxTemp);
		}
//		Log.e("SinglePhotoScreen mFilePath", mFilePath);
		gbitmap = ImageUpload.getInstance(SinglePhotoScreen.this).readFromPath(mFilePath,degree,maxSize);
		
		
		
//		gpid  =  AppUtil.getRecord(this, Constant.SINGLE_PID);
//		gFolderName =  AppUtil.getRecord(this, Constant.SINGLE_NAME);
		tv_file.setText(gFolderName);
		image1.setBackgroundDrawable(new BitmapDrawable(gbitmap));
		
	}
	/**
	 * 
	 * 方法名：initView 
	 * 功能:初始化界面 
	 * 参数： 
	 * 创建人：huanghsh 
	 * 创建时间：2012-6-3
	 */
	private void initView() {
		image1 = (ImageView) findViewById(R.id.sps_iv_image1);
		btn_right= (Button) findViewById(R.id.sps_btn_right);
		btn_right.setOnClickListener(this);
//		btn_submit_1 = (Button) findViewById(R.id.sps_btn_submit_1);
//		btn_submit_1.setOnClickListener(this);
		
		btn_submit_2 = (Button) findViewById(R.id.sps_btn_submit_2);
		btn_submit_2.setOnClickListener(this);
		
		btn_roll = (Button) findViewById(R.id.sps_btn_roll);
		btn_roll.setOnClickListener(this);
		btn_return = (Button) findViewById(R.id.sps_btn_return);
		btn_return.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				DataUtil.deleFileInFolder(ImageUpload.getInstance(SinglePhotoScreen.this).getFileDir());
					finish();
			}
		});
		btn_file = (Button) findViewById(R.id.sps_btn_file);
		btn_file.setOnClickListener(this);
		tv_file = (TextView) findViewById(R.id.sps_tv_file);
		
		String flag=AppUtil.getRecord(this, Constant.FLAG);
		//DataUtil.showShortToast(this, "flag="+flag);
		
		if("3".equals(flag)){
			sps_text_title = (TextView) findViewById(R.id.sps_text_title);
			btn_return = (Button) findViewById(R.id.sps_btn_return);
			btn_right.setText("重选");
			sps_text_title.setText("相册修改");
			//btn_return.setVisibility(View.GONE);
		}
		
		
		
		
	}

	private void initDBdata(){
    	Oper = AppUtil.getRecord(SinglePhotoScreen.this,Constant.OPERATION);
		type =AppUtil.getRecord(SinglePhotoScreen.this,Constant.TYPE);
		params =AppUtil.getRecord(SinglePhotoScreen.this,Constant.PARAMS);
		gFolderName= Constant.DefaultFileName;
		if(params.length()>0){
			parmasMap = AppUtil.combineHttpParams(params);
			wapFrom= parmasMap.get("type");
			gFolderName= AppUtil.UnicodeToGB2312(parmasMap.get("name"));
		}else{
			finish();
		}
		
	}
	@Override
	public void onClick(View v) {

		UploadProData proData;
		long gDataId;
		switch (v.getId()) {
		case R.id.sps_btn_roll:
			if(gbitmap!=null){
				gbitmap = AppUtil.rotate(gbitmap,90);
				BitmapDrawable bd = new BitmapDrawable(
						SinglePhotoScreen.this.getResources(), gbitmap);
				image1.setBackgroundDrawable(bd);
			}
			break;
//		case R.id.sps_btn_submit_1:
//			update(2);
//			btn_submit_1.setClickable(false);
//			btn_submit_2.setClickable(false);
//			break;
		case R.id.sps_btn_submit_2:
			update();
//			btn_submit_1.setClickable(false);
			btn_submit_2.setClickable(false);
			break;
		case R.id.sps_btn_file:
    		DialogUploadFile duf = new DialogUploadFile(SinglePhotoScreen.this,new OnChooseFileListener(){

				@Override
				public void setUploadFile(String path,String pid) {
					tv_file.setText(path);
					gFolderName= path;
					gpid = pid;
				}});
    		duf.show();
    		break;
		case R.id.sps_btn_right:
			if (gbitmap != null && !gbitmap.isRecycled()){
				gbitmap.recycle();
				gbitmap= null;
	 			System.gc();
			}
			
			DataUtil.deleFileInFolder(ImageUpload.getInstance(SinglePhotoScreen.this).getFileDir());
			
			
			String flag=AppUtil.getRecord(this, Constant.FLAG);
			//DataUtil.showShortToast(this, "flag="+flag);
			
			if("1".equals(flag)){
				
				Intent intent = new Intent(SinglePhotoScreen.this, CustomCamera.class);
				SinglePhotoScreen.this.startActivity(intent);
				finish();
			}
			
			if("2".equals(flag)){
				Intent intent = new Intent(SinglePhotoScreen.this, TakePhotoScreen.class);
				SinglePhotoScreen.this.startActivity(intent);
				
			}
			
			if("3".equals(flag)){
				Intent intent = new Intent(SinglePhotoScreen.this, SinglePhotoScreen.class);
				SinglePhotoScreen.this.startActivity(intent);
				
			}
			
			
			break;

		}

	}

	private void update(){
		boolean isCan = true;
//		AppUtil.saveRecord(SinglePhotoScreen.this, "this_flag", this_flag+"");
		int maxSize=0;
			proData = new UploadProData();
			infoList = new ArrayList<UploadInfo>();
    		if("2".equals(Oper)){
				String id = AppUtil.getRecord(SinglePhotoScreen.this,Constant.sid);
				String pid = AppUtil.getRecord(SinglePhotoScreen.this,Constant.Tpid);
				String url = AppUtil.getRecord(SinglePhotoScreen.this,Constant.URL_UPLOAD);
				parmasMap = new HashMap<String, String>();
				parmasMap.put("id", id);
				parmasMap.put("p_id", pid);
				parmasMap.put("url", url);
				parmasMap.put("name", Constant.DefaultFileName);
			}else  if("1".equals(Oper) && params.length()>0){//来自网络
					parmasMap = AppUtil.combineHttpParams(params);
					String fnum = parmasMap.get("num");
					String fmax = parmasMap.get("max_num");
					String maxTemp = parmasMap.get("maxsize");
					if(maxTemp!=null&& maxTemp.length()>0){
						maxSize = Integer.valueOf(maxTemp);
					}
					String name = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
					if(fnum!=null && fmax!=null){
						int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
						if(re==0){
							DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片数量已满，无法上传");
							isCan = false;
							finish();
						}
					}
					
					String cuurimg=parmasMap.get("cuurimg");
					if(cuurimg!=null && cuurimg.length()>0){
						int temp = Integer.valueOf(cuurimg);
						temp=temp+1+curing;
						parmasMap.put("cuurimg", temp+"");
					}
			}
    		parmasMap.put("fName", new Date().getTime()+"");
    		
    		//判断是否图片
    		if (gbitmap != null && !gbitmap.isRecycled()){
				
			}else{
				DataUtil.showShortToast(getApplicationContext(), "图片获取失败，请重试");
				isCan = false;
				finish();
				
			}
    		
    		if(isCan){
				
    			File file = ImageUpload.getInstance(SinglePhotoScreen.this).formatFileFromBitmap(gbitmap,maxSize);
				File sfile = ImageUpload.getInstance(SinglePhotoScreen.this).formatFileFromBitmapSmall(gbitmap);
				
				UploadInfo info = new UploadInfo();
				info.setParmasMap(parmasMap);
				info.setFile(file);
				info.setSmallFile(sfile);
				
				
				
				infoList.add(info);
				proData.setInfoList(infoList);
	    		proData.setTotal(infoList.size());
	    		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
	    		proData.setCur(0);
	    		proData.setFailNum(0);
	    		proData.setFileName(AppUtil.UnicodeToGB2312(parmasMap.get("name")));
	    		if("2".equals(type)){
					proData.setType("修改");
				}else{
					proData.setType("上传");
				}
	    		sendImage();
	    		canTemp++;
	    		curing++;
	    		Intent intent3 = new Intent(SinglePhotoScreen.this, UploadInfoScreen.class);
				startActivity(intent3);
				finish();
    		}
	}
    		private  void sendImage(){
    	    	Thread t = new Thread() {
    				@Override
    				public void run() {
    					UploadProDataDaoImpl daoImpl = new UploadProDataDaoImpl(SinglePhotoScreen.this);
    					boolean isCancle = false;
    					boolean isFail = false;
    					Long id = daoImpl.insert(proData);
    					AppUtil.sendMesToActivity(SinglePhotoScreen.this,1,"");
    					ArrayList<UploadInfo> list = proData.getInfoList();
    					int j=0;
    					int fail=0;
    					for(int i=0;i<list.size();i++){
    						j++;
    						UploadProData temp = daoImpl.get(id.intValue());
    						if(temp==null){
    							isCancle =true;
    							break;
    						}
    						//防止数据库锁，暂停
    						try {
    							sleep(100);
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    						
    						UploadInfo info = list.get(i);
    						if(temp.getFlag()==1){
    							break;
    						}else{
    							String result = HttpService.getInstance(SinglePhotoScreen.this).uploadPicture(info);
    							Log.e("SinglePhotoScreen", result+"");
    							UploadResult re=getResult(result);
    							if(re.ok){
    								temp.setCur(j);
    							}else{//失败
    								try {
    									sleep(1500);
    								} catch (InterruptedException e) {
    									e.printStackTrace();
    								}
    								String result2 = HttpService.getInstance(SinglePhotoScreen.this).uploadPicture(info);
    								UploadResult re2=getResult(result2);
    								if(re2.ok){
    									temp.setCur(j);
    								}else{
    									fail++;
    									isFail = true;
    									temp.setRemark(re.desc);
    									AppUtil.sendMesToActivity(SinglePhotoScreen.this,3,re.desc);
    								}
    								
    							}
    							temp.setFailNum(fail);
    							
    							daoImpl.update(temp);
    							//防止数据库锁，暂停
    							try {
    								sleep(100);
    							} catch (InterruptedException e) {
    								e.printStackTrace();
    							}
    							AppUtil.sendMesToActivity(SinglePhotoScreen.this,1,"");
    						}
    						
    					}
    					proData = null;
    					if(!isCancle){
    						//上传循环结束，若记录不是中断记录，则删除
    						if(!isFail){
    							try {
    								sleep(100);
    							} catch (InterruptedException e) {
    								e.printStackTrace();
    							}
    							AppUtil.saveRecord(SinglePhotoScreen.this, "fabu", "true");
    							   
    							AppUtil.sendMesToActivity(SinglePhotoScreen.this,2,"上传成功");
    						}
    						
    					}else{
    						
    					}
    				}
    	    		
    	    	};
    	    	t.start();
    	    }
    	    
    	    private static UploadResult getResult(String result){
    	    	UploadResult re = new UploadResult();
    	    	Log.e("122111",result.toString());
    	    	if(result==null){
    	    		re.ok= false;
    	    		re.desc="网络异常，上传失败";
    	    		return re;
    	    	}
    	    	Log.e("111111",result.toString());
    	    	//正式
    	    	String json = result.toString();
    			  try {
    				String ret = new JSONObject(json).getString("ret");
    				if("0".equals(ret)){
    					re.ok= false;
    				
    				} else if("1".equals(ret)){
    					String code = new JSONObject(json).getString("result");
    					String desc = new JSONObject(json).getString("desc");
    					if("0".equals(code)){
    						re.ok= false;
    						re.desc = desc;
    					}else if("1".equals(code)){
    						//成功
    					}else if("2".equals(code)){
    						re.ok= false;
    						re.desc = desc;
    					}
    					
    				}
    			} catch (JSONException e) {
    				e.printStackTrace();
    				re.ok= false;
    				re.desc="网络异常，上传失败";
    				return re;
    			}
    			return re;
    	    }
	
}
